import React from 'react';
import { connect } from 'dva'
import moment from 'moment'

import Title from 'components/Title'
import Chart from 'components/Chart'
import Tools from 'utils/tools';

import { config } from 'utils';
const { scada, CMR } = config;
const { DdToken } = scada;
const { AlarmStation } = CMR;

const format = 'YYYY'
const nowTimeStamp = Date.now();
const now = new Date(nowTimeStamp);
const time = moment(now).format(format)

@connect(({ watermeter }) => ({ ...watermeter }))
class StatisticsAlarmRadio extends React.Component {
  echartsConf = {
    chart: {
      type: 'Common2', dataSource: 'StationAlarmResourceUnique_Statistics',
      columns: {
        yAxis: [{ name: '%' }],
        xAxis: { field: 'time', format: 'M月' },
      },
      color: ['74, 144, 255', '98, 203, 120', '246, 214, 71', '231, 62, 62'],
      other: { showLegend: true },
    },
    server: { type: 'watermeter/queryStationAlarm', payload: { Token: DdToken, type: 'Unique_Statistics' } },
  }

  constructor(props) {
    super(props);

    let time;
    if ('defaultValue' in props) {
      time = props.defaultValue;
    }
    this.state = {
      time,
      monthList: []
    };
  }
  componentDidMount() {
    this.init();
  }
  init = () => {
    const { time } = this.state;
    const monthList = Tools.getFullMonth(time);
    this.setState({
      monthList
    }, () => {
      this.setDateECharts()
    })
  }
  componentWillReceiveProps(nextProps) {
    if (this.props.defaultValue !== nextProps.defaultValue) {
      if (nextProps.defaultValue) {
        this.setState({
          time: nextProps.defaultValue
        }, () => {
          this.init()
        })
      }
    }
  }

  // 图表
  setDateECharts = () => {
    const { echartsConf } = this;
    const { server } = echartsConf;
    if (server) this.queryServer(server);
  }

  // 处理echarts配置请求
  queryServer = async (server) => {
    const { time: year } = this.state;
    const begin = moment(year).startOf('year').unix();
    const end = moment(year).endOf('year').unix();

    let { payload } = server;
    Object.assign(payload, {
      begin,
      end
    })
    Object.assign(server, { payload })
    await this.props.dispatch(server);
  }

  getData = (dataResourceArr, seriesItems, monthList) => {
    let result = {}

    let dataArr = [];
    let timeArr = [];
    if(Array.isArray(dataResourceArr) && Array.isArray(seriesItems)){
      seriesItems.map((items,idx) => {
        const curResource = dataResourceArr.filter(resource =>{
          if(items['realname'] === resource['factory']) return resource;
        })
        const data =[]
        monthList.forEach(ele => {
          // 每月第一天 和 最后一天
          const startTimestamp = moment(moment(ele).startOf('month')).unix();
          const endTimestamp = moment(moment(ele).endOf('month')).unix();
          const supplyData = Tools.SumRangeTotal(dataResourceArr, [startTimestamp, endTimestamp])
          const sellData = Tools.SumRangeTotal(curResource, [startTimestamp, endTimestamp])
          const radio = supplyData === 0 ? 0 :(sellData/supplyData * 100).toFixed(2) * 1;
          data.push(radio)
          // 处理时间
          if(idx === 0) timeArr.push(moment(ele).format('M月'))
        })
        const params = Object.assign(items, { data });
        dataArr.push(params)
      })
    }
    Object.assign(result, {time: timeArr, data: dataArr })
    return result;
  }

  render() {
    const { echartsConf, props, state } = this;
    const { monthList } = state;

    const { chart, extra } = echartsConf;
    const { type: chartType, dataSource, columns, color, other } = chart;

    const Resource = this.getData(props[dataSource], AlarmStation, monthList)
    let ReColumns = columns;
    Object.assign(ReColumns, { seriesItems: AlarmStation })
    return (
      <Title title={'异常表占比情况'}>
        <Chart
          type={chartType}
          color={color}
          columns={ReColumns}
          dataSource={Resource}
          extra={extra}
          other={other}
        />
      </Title>
    )
  }
}

export default StatisticsAlarmRadio;
